﻿using DevExpress.Data;
using DevExpress.Mvvm;
using DevExpress.Mvvm.Native;
using DevExpress.XtraRichEdit.Commands;
using FastExpressionCompiler.LightExpression;
using HandyControl.Controls;
using Newtonsoft.Json;
using PlaceOrder_Core.Helper;
using PlaceOrder_Core.PlaceOrderModels;
using PlaceOrder_Core.Services.Instances;
using PlaceOrder_Core.Services.Interfaces;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PlaceOrder_Client.ViewModels
{
    //public class TradeAmountConfig
    //{
    //    public string TsCode { get; set; }

    //    public int TradeAmount { get; set; }
    //}

    public class TradeAmountConfigViewModel:BindableBase
    {
        #region 依赖属性
        private decimal volumeValue=2000;

        public decimal VolumeValue
        {
            get { return volumeValue; }
            set { volumeValue = value; RaisePropertiesChanged(); }
        }


        private List<string> _tsCodes;
        public List<string> TsCodes
        {
            get { return _tsCodes; }
            set
            {
                if (_tsCodes != value)
                {
                    _tsCodes = value;
                    RaisePropertyChanged();
                }
            }
        }

        /// <summary>
        /// 券号
        /// </summary>
        private string bondNumber;

        public string BondNumber
        {
            get { return bondNumber; }
            set { bondNumber = value; RaisePropertyChanged(); }
        }
        private ObservableCollection<UserTradeVolumeConfig> _tradeAmountConfigs;

        public ObservableCollection<UserTradeVolumeConfig> TradeAmountConfigs
        {
            get { return _tradeAmountConfigs; }
            set
            {
                if (_tradeAmountConfigs != value)
                {
                    _tradeAmountConfigs = value;
                    RaisePropertiesChanged();
                }
            }
        }

        private UserTradeVolumeConfig selectedTrade;

        public UserTradeVolumeConfig SelectedTrade
        {
            get { return selectedTrade; }
            set { selectedTrade = value;RaisePropertiesChanged();this.BondNumber = selectedTrade?.Tscode; }
        }

        #endregion
        private readonly IDailyData _dailyData;
        public TradeAmountConfigViewModel(IDailyData dailyData)
        {
            _dailyData = dailyData;
            InitTradeAmountConfig();
            InitCommand();
        }
        public DelegateCommand<UserTradeVolumeConfig> DeleteCommand { get; set; }
        public DelegateCommand AddCommand { get; set; }
        private void InitCommand()
        {
            DeleteCommand = new DelegateCommand<UserTradeVolumeConfig>(DeleteConfig);
            AddCommand = new DelegateCommand(AddConfig);
        }

        public void  AddConfig()
        {
            try
            {
                if (this.TsCodes == null)
                {
                    return;
                }
                if (this.BondNumber == null)
                {
                    Growl.WarningGlobal("请选中券码");
                    return;
                }
                if (this.VolumeValue < 2000)
                {
                    Growl.WarningGlobal("交易量默认不能小于2000，请检查");
                    return;
                }
                UserTradeVolumeConfig existingConfig = TradeAmountConfigs?.FirstOrDefault(c => c.Tscode == this.BondNumber);

                if (existingConfig != null)
                {
                    // Update existing config
                    existingConfig.Volume = this.VolumeValue;

                    // Update in database
                    if (_dailyData.UpdateUserTradeVolumeConfig(existingConfig))
                    {
                        Growl.SuccessGlobal($"更新券码{existingConfig.Tscode},量-{existingConfig.Volume}成功！");
                    }

                }
                else
                {
                    // Add new config
                    UserTradeVolumeConfig newConfig = new UserTradeVolumeConfig
                    {
                        Volume = this.VolumeValue,
                        Tscode = this.BondNumber
                    };

                    if (_dailyData.AddUserTradeVolumeConfig(newConfig))
                    {
                        if(TradeAmountConfigs==null)
                        {
                            TradeAmountConfigs = new ObservableCollection<UserTradeVolumeConfig>();
                        }
                        TradeAmountConfigs.Add(newConfig);
                        Growl.SuccessGlobal($"添加券码{newConfig.Tscode},量-{newConfig.Volume}成功！");
                    }
                    else
                    {
                        Growl.WarningGlobal("添加失败，请重试");
                    }
                }

                RefreshConfig();
            }
            catch(Exception ex)
            {
                Growl.WarningGlobal($"添加异常，{ex.Message}");
                AppLog.WriteError($"添加券码异常，{ex.Message}，{ex.StackTrace}");

            }

        }

        private void RefreshConfig()
        {
            OrderListViewModel.VolumeConfigs =_dailyData.GetUserTradeVolumeConfig(UserHelper.UserID);

            this.TradeAmountConfigs = new ObservableCollection<UserTradeVolumeConfig>(
     OrderListViewModel.VolumeConfigs
         .GroupBy(x => x.Tscode)
         .Select(g => g.First())
 );

        }

        private void DeleteConfig(UserTradeVolumeConfig config)
        {
            if(_dailyData.RemoveUserTradeVolumeConfig(config))
            {
                this.TradeAmountConfigs = _dailyData.GetUserTradeVolumeConfig(UserHelper.UserID).ToObservableCollection();
                Growl.SuccessGlobal($"移除券码--{config.Tscode}的交易配置成功");
            }
            RefreshConfig();
        }
        private const string ConfigFilePath = "TradeAmountConfig.json";
        private void InitTradeAmountConfig()
        {
            TsCodes = OrderListViewModel.WhiteTscodeList;
            if(OrderListViewModel.VolumeConfigs!=null&& OrderListViewModel.VolumeConfigs.Count>0)
            {
                this.TradeAmountConfigs = new ObservableCollection<UserTradeVolumeConfig>(
OrderListViewModel.VolumeConfigs
   .GroupBy(x => x.Tscode)
   .Select(g => g.First())
);
            }
      
            //if (File.Exists(ConfigFilePath))
            //{
            //    var json = File.ReadAllText(ConfigFilePath);
            //    var configs = JsonConvert.DeserializeObject<ObservableCollection<TradeAmountConfig>>(json)
            //                   ?? new ObservableCollection<TradeAmountConfig>();
            //    TradeAmountConfigs = configs;
            //}
            //else
            //{
            //    // 创建一个默认配置

            //    // 保存默认配置到文件
            //    SaveTradeAmountConfigs();
            //}
        }
        private void SaveTradeAmountConfigs()
        {
            var json = JsonConvert.SerializeObject(TradeAmountConfigs, Formatting.Indented);
            File.WriteAllText(ConfigFilePath, json);
        }
        public void AddTradeAmountConfig(UserTradeVolumeConfig config)
        {
            try
            {
                if (config == null) return;
                // Check if the config already exists to avoid duplicates
                var existingConfig = TradeAmountConfigs.FirstOrDefault(c => c.Tscode == config.Tscode);
                if (existingConfig != null)
                {
                    // Optionally, update the existing config's trade amount if needed
                    existingConfig.Volume = config.Volume;
                    Growl.SuccessGlobal($"成功修改券码{config.Tscode},默认交易量变为：{config.Volume}");
                }
                else
                {
                    TradeAmountConfigs.Add(config);
                    Growl.SuccessGlobal($"成功添加券码{config.Tscode},默认交易量设为：{config.Volume}");
                }

                // 保存更新后的数据到文件
                SaveTradeAmountConfigs();
            }
            catch(Exception ex)
            {
                Growl.SuccessGlobal($"添加券码{config.Tscode},交易量：{config.Volume} 失败，{ex.Message}");
                AppLog.WriteError($"添加券码{config.Tscode},交易量：{config.Volume} 失败，{ex.Message}");
            }
            
        }


        public void RemoveTradeAmountConfig(string tsCode)
        {
            var config = TradeAmountConfigs.FirstOrDefault(c => c.Tscode == tsCode);
            if (config != null)
            {
                TradeAmountConfigs.Remove(config);
            }
            // 保存更新后的数据到文件
            SaveTradeAmountConfigs();
        }

    }
}
